package com.ldc.framework.activity

import android.content.Context
import android.content.Intent
import android.os.Message
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.ldc.commonlibs.conf.AppConf
import com.ldc.commonlibs.conf.RouteConf
import com.ldc.commonlibs.listener.OnRowListener
import com.ldc.commonlibs.listener.OnRowListener2
import com.ldc.commonlibs.uts.ApiUtils
import com.ldc.commonlibs.uts.MessageUts
import com.ldc.commonlibs.uts.ViewModelUtils
import com.ldc.commonres.common.VBMActivity
import com.ldc.commonres.views.StateViewLayout
import com.ldc.framework.R
import com.ldc.framework.adapter.ArticleAdapter
import com.ldc.framework.databinding.FrameworkActivityArticleListBinding
import com.ldc.framework.model.ArticleModel
import com.ldc.framework.viewmodel.FrameworkViewModelBase
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener

class ArticleListActivity : VBMActivity<FrameworkActivityArticleListBinding, FrameworkViewModelBase>() {
    private var page: Int = 0
    private var cid: String? = ""
    private var articleAdapter: ArticleAdapter? = null
    override fun processMessage(msg: Message): Boolean {
        when (msg.what) {
            REFRESH_CODE -> {
                getData()
            }
        }
        return super.processMessage(msg)
    }

    companion object {
        private const val REFRESH_CODE = 0x123
        private const val ARG_CID = "cid"
        private const val ARG_TITLE = "title"
        fun start(context: Context, title: String, cid: String) {
            context.startActivity(Intent(context, ArticleListActivity::class.java).also {
                it.putExtra(ARG_CID, cid)
                it.putExtra(ARG_TITLE, title)
            })
        }
    }

    override fun initStateViewLayout(): StateViewLayout? =
        StateViewLayout.Companion.init(this, R.id.content_view)

    override fun main() {
        addOnReTryListener(object : OnRowListener<Int> {
            override fun onRow(v: View, data: Int) {
                page = 0
                MessageUts.sendMessage(getHandler(), REFRESH_CODE)
            }
        })
        intent?.let {
            cid = it.getStringExtra(ARG_CID)!!
            title = it.getStringExtra(ARG_TITLE)!!
        }
        initAdapter()
        viewBind?.let {
            it.contentView.refreshView.also { rv ->
                rv.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
                    override fun onRefresh(refreshLayout: RefreshLayout) {
                        page = 0
                        MessageUts.sendMessage(getHandler(), REFRESH_CODE)
                    }

                    override fun onLoadMore(refreshLayout: RefreshLayout) {
                        page += 1
                        MessageUts.sendMessage(getHandler(), REFRESH_CODE)
                    }
                })
            }
            // 标题
            it.topBar.also { topBar ->
                topBar.tvName.text = "$title"
                topBar.flBack.setOnClickListener() { finish() }
            }
        }

        MessageUts.sendMessage(getHandler(), REFRESH_CODE)


    }

    override fun createViewBinding(): FrameworkActivityArticleListBinding =
        FrameworkActivityArticleListBinding.inflate(layoutInflater)

    override fun createViewModel(): FrameworkViewModelBase =
        ViewModelUtils.create(this, FrameworkViewModelBase::class.java)


    //
    private fun getData() {
        showLoadingView()
        viewModel?.articleList(page, "$cid")?.observe(this) {
            showContentView()
            viewBind?.contentView?.refreshView?.also { rv ->
                if (rv.state.isOpening) {
                    rv.finishLoadMore()
                    rv.finishRefresh()
                }
                rv.setNoMoreData(page == it.data?.pageCount)
            }
            if (ApiUtils.isSuccess(it)) {
                if (page == 0) {
                    articleAdapter?.newData(it.data?.datas)
                } else {
                    articleAdapter?.addNewData(it.data?.datas)
                }
            }
            if (articleAdapter?.isEmptyData()!!) {
                showEmptyView()
            }
        }
    }

    private fun initAdapter() {
        articleAdapter = ArticleAdapter().also { adapter ->
            adapter.addOnRowListener(object : OnRowListener<ArticleModel> {
                override fun onRow(v: View, data: ArticleModel) {
                    ARouter
                        .getInstance()
                        .build(RouteConf.WebViewRoute.startEnter)
                        .withString(AppConf.ARG_TITLE, data.title)
                        .withString(AppConf.ARG_URL, data.link).navigation()
                }
            })
            adapter.addCollectRowListener(object : OnRowListener2<ArticleModel, Int> {
                override fun onRow(v: View, data: ArticleModel, data2: Int) {
                    if (data.collect) {
                        // 取消收藏
                        viewModel?.uncollectOriginId("${data.id}")
                            ?.observe(this@ArticleListActivity) {
                                if (ApiUtils.isSuccess(it)) {
                                    adapter.changeDataItem(data2)
                                }
                            }
                    } else {
                        // 收藏
                        viewModel?.collect("${data.id}")?.observe(this@ArticleListActivity) {
                            if (ApiUtils.isSuccess(it)) {
                                adapter.changeDataItem(data2)
                            }
                        }
                    }
                }

            })
        }
        viewBind?.contentView?.rv?.recyclerview?.also {
            it.adapter = articleAdapter
            it.setHasFixedSize(true)
            it.layoutManager = LinearLayoutManager(
                this, LinearLayoutManager.VERTICAL, false
            )
        }

    }

}